package com.loie.xcx.interceptor;


import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.loie.xcx.comm.JsonResult;
import com.loie.xcx.model.bo.TokenInfoBO;
import com.loie.xcx.util.TokenUtils;
import io.netty.util.internal.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.ws.RequestWrapper;
import java.util.*;

@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    private final Logger logger = LoggerFactory.getLogger(LoginInterceptor.class);
//
//    @Override
//    public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
//            throws Exception {
//    }
//
//    @Override
//    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
//            throws Exception {
//    }
//
//    @Override
//    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object arg2) throws Exception {
//        RequestWrapper requestWrapper = new RequestWrapper(request);
//        String body = requestWrapper.getBodyString();
//        JSONObject jsonObject = JSONObject.parseObject(body);
//        String thirdAppId = jsonObject.getString("thirdAppId");
//        if (StringUtils.isBlank(thirdAppId)) {
//            log.error("appId不能为空...........");
//            ServletUtils.renderString(response, JSON.toJSONString(Result.error(ErrorCode, "thirdAppId不能为空")));
//            return false;
//        } else {
//            //TODO 验证 appID是否存在  后续接入appID的查询
//            if (!APP_ID.equals(thirdAppId)) {
//                log.error("appId非法或者不存在");
//                ServletUtils.renderString(response, JSON.toJSONString(Result.error(ErrorCode, "thirdAppId非法或者不存在")));
//                return false;
//            }
//        }
//
//        //加密方式
//        String signType = jsonObject.getString("signType");
//        SignTypeEnum signTypeEnum = SignTypeEnum.getSignType(signType);
//        if (null == signTypeEnum) {
//            log.error("签名加密暂时只支持SHA256、SHA1和MD5");
//            ServletUtils.renderString(response, JSON.toJSONString(Result.error(ErrorCode, "签名加密暂时只支持SHA256、SHA1和MD5")));
//            return false;
//        }
//
//        //时间戳
//        String timestampStr = jsonObject.getString("timestamp");
//        if (StringUtils.isBlank(timestampStr)) {
//            log.error("timestamp不能为空...........");
//            ServletUtils.renderString(response, JSON.toJSONString(Result.error(ErrorCode, "timestamp不能为空")));
//            return false;
//        }
//
//        //参数签名
//        String sign = jsonObject.getString("sign");
//        if (StringUtils.isBlank(sign)) {
//            log.error("sign不能为空...........");
//            ServletUtils.renderString(response, JSON.toJSONString(Result.error(ErrorCode, "sign不能为空")));
//            return false;
//        }
//        String nonce = jsonObject.getString("nonce");
//        if (StringUtils.isBlank(nonce)) {
//            log.error("nonce不能为空...........");
//            ServletUtils.renderString(response, JSON.toJSONString(Result.error(ErrorCode, "nonce不能为空")));
//            return false;
//        }
//
//        //随机数非法
//        if (size!=StringUtils.length(nonce)) {
//            log.error("nonce位数应该为32位");
//            ServletUtils.renderString(response, JSON.toJSONString(Result.error(ErrorCode, "nonce位数应该为32位")));
//            return false;
//        }
//
//
//
//
//        //1.前端传过来的时间戳与服务器当前时间戳差值大于180，则当前请求的timestamp无效
//        if (DateUtils.isTimeOut(timestampStr)) {
//            log.debug("timestamp无效...........");
//            ServletUtils.renderString(response, JSON.toJSONString(Result.error(ErrorCode, "timestamp无效")));
//            return false;
//        }
//        //2.通过判断redis中的nonce，确认当前请求是否为重复请求，控制API接口幂等性
//        boolean nonceExists = redisUtils.hasKey(nonce);
//        if (nonceExists) {
//            log.debug("nonce重复...........");
//            ServletUtils.renderString(response, JSON.toJSONString(Result.error(ErrorCode, "重复的请求")));
//            return false;
//        }
//        //3.通过后台重新签名校验与前端签名sign值比对，确认当前请求数据是否被篡改
//
//        String bizContent = jsonObject.getString("bizContent");
//
//        String signEncrypt = SignUtil.getSign(thirdAppId, APP_KEY, signType, timestampStr,
//                bizContent,nonce);
//
//        if (!(sign.equals(signEncrypt))) {
//            log.debug("sign签名校验失败...........");
//            ServletUtils.renderString(response, JSON.toJSONString(Result.error(ErrorCode, "sign签名校验失败")));
//            return false;
//        }
//        //4.将nonce存进redis
//        redisUtils.set(NONCE_KEY + nonce, nonce, 120);
//        log.debug("签名校验通过，放行...........");
//        //5.放行
//        return true;
//
//
//
////
////        httpServletResponse.setCharacterEncoding("UTF-8");
////
////        //验证签名
////        boolean pass = validateSign(httpServletRequest);
////        if (pass) {
////            return true;
////        } else {
////            logger.warn("签名认证失败，请求接口：{}，请求IP：{}，请求参数：{}",
////                    httpServletRequest.getRequestURI(), getIpAddress(httpServletRequest), JSON.toJSONString(httpServletRequest.getParameterMap()));
////
////            JsonResult result = new JsonResult(JsonResult.UNLOGIN, "签名认证失败");
////            httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
////            httpServletResponse.getWriter().write(JSONObject.toJSONString(result));
////            return false;
////        }
//
//
//    }
//
//    /**
//     * 一个简单的签名认证，规则：
//     * 1. 将请求参数按ascii码排序
//     * 2. 拼接为a=value&b=value...这样的字符串（不包含sign）
//     * 3. 混合密钥（secret）进行md5获得签名，与请求的签名进行比较
//     */
//    private boolean validateSign(HttpServletRequest request) {
//        String requestSign = request.getParameter("sign");//获得请求签名，如sign=19e907700db7ad91318424a97c54ed57
//        if (StringUtils.isEmpty(requestSign)) {
//            return false;
//        }
//        List<String> keys = new ArrayList<String>(request.getParameterMap().keySet());
//        keys.remove("sign");//排除sign参数
//        Collections.sort(keys);//排序
//
//        StringBuilder sb = new StringBuilder();
//        for (String key : keys) {
//            sb.append(key).append("=").append(request.getParameter(key)).append("&");//拼接字符串
//        }
//        String linkString = sb.toString();
//        linkString = StringUtils.substring(linkString, 0, linkString.length() - 1);//去除最后一个'&'
//
//        String secret = "Potato";//密钥，自己修改
//        String sign = DigestUtils.md5Hex(linkString + secret);//混合密钥md5
//
//        return StringUtils.equals(sign, requestSign);//比较
//    }
//
//    private String getIpAddress(HttpServletRequest request) {
//        String ip = request.getHeader("x-forwarded-for");
//        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
//            ip = request.getHeader("Proxy-Client-IP");
//        }
//        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
//            ip = request.getHeader("WL-Proxy-Client-IP");
//        }
//        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
//            ip = request.getHeader("HTTP_CLIENT_IP");
//        }
//        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
//            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
//        }
//        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
//            ip = request.getRemoteAddr();
//        }
//        // 如果是多级代理，那么取第一个ip为客户端ip
//        if (ip != null && ip.indexOf(",") != -1) {
//            ip = ip.substring(0, ip.indexOf(",")).trim();
//        }
//
//        return ip;
//    }
}
